package springboot.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;
import springboot.Tools.Date.Day;
import springboot.Tools.Date.StartAndEndTime;
import springboot.Tools.time;
import springboot.doMain.WxGroupChatAdmin;

import java.util.*;


public class WXWorkApi {
	
	public static String getToken() {
		String stringToken = HttpClient
						// 请求方式和请求url
						.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww81027566eeda4f16&corpsecret=eB4jIG2ltRuhlkN8TIgBjn8OiJbTnds2SLjz2t_1F2M")
						.asString();
		return getData(stringToken, "access_token");
	}
	
	public static String getGroupList() {
		String getRequest = HttpClient
						.get("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=" + getToken())
						.asString();
		return isGetData(getRequest) ? getRequest : null;
	}
	
	
	public static String getData(String response, String param) {
		JSONObject jsonObject;
		try {
			jsonObject = JSON.parseObject(response);
		} catch (Exception exception) {
			return null;
		}
		int errCode;
		String errMsg;
		try {
			assert jsonObject != null;
			errCode = jsonObject.getInteger("err" + "code");
			errMsg = jsonObject.getString("err" + "msg");
		} catch (Exception e) {
			System.err.println("http请求返回值，解析出错 = " + e);
			return null;
		}
		if (errCode == 0) {
			return jsonObject.getString(param);
		} else {
			System.err.println("errMsg = " + errMsg);
		}
		return null;
	}
	
	
	//  返回值是否正确
	public static boolean isGetData(String response) {
		JSONObject jsonObject = JSON.parseObject(response);
		int errCode;
		String errMsg;
		try {
			errCode = jsonObject.getInteger("err" + "code");
			errMsg = jsonObject.getString("err" + "msg");
		} catch (Exception e) {
			System.err.println("http请求返回值，解析出错 = " + e);
			return false;
		}
		if (errCode == 0) {
			return true;
		} else {
			System.err.println("errMsg = " + errMsg);
		}
		return false;
	}
	
	/**
	 * @param chat_id 通过id获取群组信息
	 * @return 群组信息
	 */
	public static String getGroupInfo(String chat_id) {
		return getGroupInfo(chat_id, getToken());
	}
	
	
	public static String getGroupInfo(String chat_id, String token) {
		Map<String, Object> map = new HashMap<>();
		map.put("chat_id", chat_id);
		map.put("need_name", "1");
		JSONObject jsonObject = new JSONObject(map);
		String getRequest = HttpClient
						.textBody("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=" + token)
						.json(jsonObject)
						.asString();
		return getData(getRequest, "group_chat");
	}
	
	public static String getUserInfo(String external_userid) {
		return getUserInfo(external_userid, getToken());
	}
	
	public static String getUserInfo(String external_userid, String token) {
		String s = HttpClient.get("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=" + getToken() + "&external_userid=" + external_userid)
						.asString();
		return getData(s, "external_contact");
	}
	
	/*默认查找部门id为1的所有员工（合宙：id=1）*/
	public static String getDepartmentInfo() {
		return getDepartmentInfo(1);
	}
	
	/*查找某部门id下所有的员工*/
	public static String getDepartmentInfo(int department_id) {
		String s = HttpClient.get("https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + getToken() + "&department_id=" + department_id + "&fetch_child=FETCH_CHILD")
						.asString();
		return getData(s, "user" + "list");
	}
	
	public static void main(String[] args) {
		String departmentInfo = getDepartmentInfo(5);
		System.out.println(departmentInfo);
	}
	
	public static String getDepartmentList() {
		String s = HttpClient.get("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + getToken())
						.asString();
		return getData(s, "department");
	}
	
	public String getGroupChat() {
		
		return null;
	}
	
	/*
	 * 获取群聊数据，以日为单位
	 * */
	public static String getSellerDataByDay(int dayDiff) {
		Day day = StartAndEndTime.getDay(-dayDiff);
		String startTime = day.getDayStartTime().getTime() / 1000 + "";
		String endTime = day.getDayEndTime().getTime() / 1000 + "";
		return getSellerDataByDay(startTime, endTime, null);
	}
	
	public static String getSellerDataByDay(int dayDiff, String adminId) {
		Day day = StartAndEndTime.getDay(-dayDiff);
		String startTime = day.getDayStartTime().getTime() / 1000 + "";
		String endTime = day.getDayEndTime().getTime() / 1000 + "";
		return getSellerDataByDay(startTime, endTime, adminId);
	}
	
	/*
	 * 获取群聊数据，以日为单位
	 * */
	public static String getSellerDataByDay(String startTime, String endTime, String adminId) {
		String getRequest = HttpClient
						.textBody("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic_group_by_day?access_token=" + getToken())
						.text("{\n" +
										"    \"day_begin_time\": " + startTime + ",\n" +
										"    \"day_end_time\": " + endTime + ",\n" +
										"    \"owner_filter\": {\n" + (adminId == null ? "" : "\"userid_list\": [\"" + adminId + "\"]") +
										"    }\n" +
										"}")
						.asString();
		System.out.println("adminId = " + adminId);
		return getData(getRequest, "items");
	}
	
	
	public static String getSellerDataByDay(String startTime, String endTime) {
		return getSellerDataByDay(startTime, endTime, null);
	}
	
	
	public static httpRes getWeekData(Date day_begin_time, Date day_end_time) {
		String startTime = (day_begin_time.getTime() / 1000) + "";
		long now = new Date().getTime() / 1000 - 3600 * 24;
		long end = day_end_time.getTime() / 1000 - 3600 * 24 + 1;
		String endTime = now < end ? now + "" : end + "";
		String weekDataString = getSellerDataByDay(startTime, endTime);
		httpRes httpRes = new httpRes(weekDataString);
		httpRes.setStartTime(time.dateFormat(time.StringToFormatDate(startTime), 1));
		httpRes.setEndTime(time.dateFormat(time.StringToFormatDate(endTime), 1));
		return httpRes;
	}
	
	public static httpRes getWeekData(Day day) {
		return getWeekData(day.getDayStartTime(), day.getDayEndTime());
	}
	
	
	/*
	 * 获取多少天前的群聊数据统计，以群主聚合
	 * */
	public static List<WxGroupChatAdmin> getGroupDataByAdminString(int dayDiff) {
		Day day = StartAndEndTime.getDay(-dayDiff);
		String startTime = day.getDayStartTime().getTime() / 1000 + "";
		String endTime = day.getDayEndTime().getTime() / 1000 + "";
		JSONArray o = JSONArray.parseArray(getGroupDataByAdminString(startTime, endTime));
		List<WxGroupChatAdmin> wxGroupChatAdmins = new ArrayList<>();
		if (o == null) {
			return null;
		}
		o.forEach(o1 -> {
			if (o1 == null) {
				return;
			}
			WxGroupChatAdmin wxGroupChatAdmin = WxGroupChatAdmin.getInstance(o1);
			if (wxGroupChatAdmin != null) {
				wxGroupChatAdmin.setDate(day.getDayStartTime());
				wxGroupChatAdmin.setTimeStamp(day.getDayStartTime().getTime() / 1000);
				wxGroupChatAdmins.add(wxGroupChatAdmin);
			}
		});
		return wxGroupChatAdmins;
	}
	
	/*
	 * 获取群聊数据统计，以群主聚合
	 * */
	public static String getGroupDataByAdminString(String startTime, String endTime) {
		String getRequest = HttpClient
						.textBody("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic?access_token=" + getToken())
						.text("{\n" +
										"    \"day_begin_time\": " + startTime + ",\n" +
										"    \"day_end_time\": " + endTime + ",\n" +
										"    \"owner_filter\": {\n" +
										"    }\n" +
										"}")
						.asString();
		return getData(getRequest, "items");
	}
	
	
}
